import pygame
import random

# 初始化pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
HELICOPTER_WIDTH = 50
HELICOPTER_HEIGHT = 30
OBSTACLE_WIDTH = 50
OBSTACLE_HEIGHT = 20
OBSTACLE_SPEED = 3
HELICOPTER_SPEED = 5

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("直升机游戏")

# 直升机类
class Helicopter:
    def __init__(self):
        self.x = 50
        self.y = HEIGHT // 2
        self.width = HELICOPTER_WIDTH
        self.height = HELICOPTER_HEIGHT

    def move_up(self):
        if self.y > 0:
            self.y -= HELICOPTER_SPEED

    def move_down(self):
        if self.y < HEIGHT - self.height:
            self.y += HELICOPTER_SPEED

    def draw(self):
        pygame.draw.rect(screen, BLUE, (self.x, self.y, self.width, self.height))

# 障碍物类
class Obstacle:
    def __init__(self):
        self.x = WIDTH
        self.y = random.randint(0, HEIGHT - OBSTACLE_HEIGHT)
        self.width = OBSTACLE_WIDTH
        self.height = OBSTACLE_HEIGHT

    def move(self):
        self.x -= OBSTACLE_SPEED

    def draw(self):
        pygame.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height))

    def is_off_screen(self):
        return self.x + self.width < 0

    def collides_with(self, helicopter):
        return (
            helicopter.x < self.x + self.width and
            helicopter.x + helicopter.width > self.x and
            helicopter.y < self.y + self.height and
            helicopter.y + helicopter.height > self.y
        )

# 创建直升机和障碍物列表
helicopter = Helicopter()
obstacles = []
score = 0
font = pygame.font.Font(None, 36)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(WHITE)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                helicopter.move_up()
            elif event.key == pygame.K_DOWN:
                helicopter.move_down()

    # 随机生成障碍物
    if random.randint(1, 100) < 2:
        obstacles.append(Obstacle())

    # 移动和绘制障碍物
    for obstacle in obstacles[:]:
        obstacle.move()
        obstacle.draw()
        if obstacle.is_off_screen():
            obstacles.remove(obstacle)
            score += 1
        elif obstacle.collides_with(helicopter):
            print("游戏结束，你的得分是:", score)
            running = False

    # 绘制直升机
    helicopter.draw()

    # 显示得分
    score_text = font.render(f"得分: {score}", True, BLACK)
    screen.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()